# flask4.py - 简单的Flask应用用于测试花艺AI系统 (百度语音版本)
import logging

from flask import Flask, render_template, request, jsonify, redirect, url_for
import requests
import os
import base64
import json
import time
import uuid
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.jinja_env.globals.update(hasattr=hasattr)
app.jinja_env.globals.update(getattr=getattr)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB max upload

# 确保上传文件夹存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

# 花艺AI API的URL
API_URL = "http://localhost:8000"  # 修改为你的API实际地址
logger = logging.getLogger(__name__)


@app.route('/')
def index():
    """主页，显示查询界面"""
    return render_template('index.html')


@app.route('/query', methods=['POST'])
def query():
    """处理查询请求 - 修复版"""
    try:
        # 检查是否为JSON请求
        if request.is_json:
            # JSON请求（来自JavaScript）
            data = request.get_json()
            query_text = data.get('query', '')
            generate_image = data.get('generate_image', False)
        else:
            # 表单请求
            query_text = request.form.get('query', '')
            generate_image = 'generate_image' in request.form

        # 调用API
        response = requests.post(
            f"{API_URL}/query",
            json={"query": query_text, "generate_image": generate_image}
        )

        result = response.json()

        # 根据请求类型返回对应格式
        if request.is_json:
            return jsonify(result)  # 返回JSON给JavaScript
        else:
            return render_template('result.html', query=query_text, result=result)  # 返回HTML

    except Exception as e:
        error_msg = f"处理查询时出错: {str(e)}"
        if request.is_json:
            return jsonify({"error": error_msg}), 500
        else:
            return render_template('result.html', query="", result={"error": error_msg})

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    """处理知识库文件上传"""
    if request.method == 'POST':
        if 'file' not in request.files:
            return jsonify({"error": "No file part"})

        file = request.files['file']
        if file.filename == '':
            return jsonify({"error": "No selected file"})

        if file:
            filename = secure_filename(file.filename)
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(filepath)

            # 调用API上传文件
            with open(filepath, 'rb') as f:
                files = {"file": (filename, f)}
                response = requests.post(f"{API_URL}/upload-knowledge", files=files)

            # 删除临时文件
            os.remove(filepath)

            return jsonify(response.json())

    return render_template('upload.html')


@app.route('/system-status', methods=['GET'])
def system_status():
    """系统状态API - 兼容前端期望的端点"""
    try:
        # 调用FastAPI的系统状态
        response = requests.get(f"{API_URL}/system-status")

        if response.status_code == 200:
            return jsonify(response.json())
        else:
            # 如果FastAPI不可用，返回基本状态
            return jsonify({
                "status": "running",
                "message": "Flask service is running, but FastAPI service may be unavailable",
                "speech_interaction": {
                    "asr_available": {"deepseek_asr": False},
                    "tts_available": {"xunfei_tts": False}
                }
            })
    except Exception as e:
        # 返回错误状态
        return jsonify({
            "status": "error",
            "error": str(e),
            "speech_interaction": {
                "asr_available": {"deepseek_asr": False},
                "tts_available": {"xunfei_tts": False}
            }
        }), 500

@app.route('/doubao-status', methods=['GET'])
def doubao_status():
    """豆包服务状态API"""
    try:
        response = requests.get(f"{API_URL}/doubao-status")
        if response.status_code == 200:
            return jsonify(response.json())
        else:
            return jsonify({
                "asr_service": {"configured": False},
                "tts_service": {"configured": False}
            })
    except Exception as e:
        return jsonify({
            "error": str(e),
            "asr_service": {"configured": False},
            "tts_service": {"configured": False}
        }), 500

@app.route('/train')
def train():
    """触发本地模型训练"""
    response = requests.post(f"{API_URL}/train-local-model")
    return jsonify(response.json())


@app.route('/image', methods=['GET', 'POST'])
def generate_image():
    """生成花艺图像界面"""
    if request.method == 'POST':
        prompt = request.form.get('prompt', '')
        style = request.form.get('style', 'realistic')

        # 调用API生成图像
        response = requests.post(
            f"{API_URL}/generate-image",
            json={"prompt": prompt, "style": style}
        )

        result = response.json()
        return render_template('image_result.html', result=result)

    return render_template('generate_image.html')


# 新增语音交互相关路由 (修改为百度版本)
@app.route('/speech', methods=['GET'])
def speech_interface():
    """语音交互界面"""
    # 获取支持的方言和语音
    try:
        # 获取系统状态以检查语音支持
        status_response = requests.get(f"{API_URL}/system-status")
        status = status_response.json()

        # 获取可用语音
        voices_response = requests.get(f"{API_URL}/available-voices")
        voices = voices_response.json().get("voices", {})

        return render_template(
            'updated_speech.html',
            status=status,
            voices=voices
        )
    except Exception as e:
        return jsonify({"error": f"获取语音服务信息失败: {str(e)}"})


@app.route('/speech-to-text', methods=['POST'])
def handle_speech_to_text():
    '''处理语音转文字请求 - 百度版本'''
    try:
        # 获取音频数据
        if 'audio' not in request.files:
            return jsonify({"error": "没有接收到音频文件"})

        audio_file = request.files['audio']
        dialect = request.form.get('dialect', 'mandarin')

        # 调用API进行语音识别 - 使用百度API端点
        response = requests.post(
            f"{API_URL}/speech-to-text-form",
            files={"audio": audio_file},
            data={"dialect": dialect}
        )

        return jsonify(response.json())

    except Exception as e:
        return jsonify({"error": f"语音识别失败: {str(e)}"})


@app.route('/text-to-speech', methods=['POST'])
def handle_text_to_speech():
    """处理文字转语音请求 - 百度版本"""
    try:
        data = request.get_json()
        text = data.get('text', '')
        dialect = data.get('dialect', 'mandarin')
        voice_id = data.get('voice_id')
        speed = float(data.get('speed', 1.0))

        # 调用API进行语音合成
        response = requests.post(
            f"{API_URL}/text-to-speech",
            json={
                "text": text,
                "dialect": dialect,
                "voice_id": voice_id,
                "speed": speed
            }
        )

        # 关键修改：确保即使出错也返回JSON
        if response.status_code != 200:
            return jsonify({"error": f"TTS服务返回错误: {response.status_code}"}), response.status_code

        # 返回JSON结果
        return jsonify(response.json())

    except Exception as e:
        # 捕获所有异常并返回JSON格式的错误
        return jsonify({"error": f"语音合成失败: {str(e)}"}), 500


@app.route('/speech-query', methods=['POST'])
def handle_speech_query():
    """处理语音查询请求 - 百度版本"""
    try:
        # 获取音频数据
        if 'audio' not in request.files:
            return jsonify({"error": "没有接收到音频文件"})

        audio_file = request.files['audio']
        dialect = request.form.get('dialect', 'mandarin')
        generate_image = request.form.get('generate_image') == 'true'
        voice_response = request.form.get('voice_response') == 'true'
        voice_id = request.form.get('voice_id')

        # 读取音频文件并转为base64
        audio_data = audio_file.read()
        audio_base64 = base64.b64encode(audio_data).decode('utf-8')

        # 调用API进行语音查询
        response = requests.post(
            f"{API_URL}/speech-query",
            json={
                "audio_base64": audio_base64,
                "dialect": dialect,
                "generate_image": generate_image,
                "voice_response": voice_response,
                "voice_id": voice_id
            }
        )

        # 检查响应状态码
        if response.status_code != 200:
            # 记录错误响应
            error_msg = f"API返回错误: 状态码 {response.status_code}"
            print(error_msg)
            print(f"响应内容: {response.text[:200]}...")  # 打印前200个字符以进行诊断
            return jsonify({"error": error_msg})

        # 检查Content-Type
        content_type = response.headers.get('Content-Type', '')
        if 'application/json' not in content_type:
            error_msg = f"API返回了非JSON内容: {content_type}"
            print(error_msg)
            print(f"响应内容: {response.text[:200]}...")
            return jsonify({"error": error_msg})

        try:
            result = response.json()
            return render_template('speech_result.html', result=result)
        except ValueError as e:
            # JSON解析错误
            error_msg = f"无法解析API响应为JSON: {str(e)}"
            print(error_msg)
            print(f"响应内容: {response.text[:200]}...")
            return jsonify({"error": error_msg})

    except requests.RequestException as e:
        # 网络请求错误
        return jsonify({"error": f"API请求失败: {str(e)}"})
    except Exception as e:
        # 其他错误
        return jsonify({"error": f"语音查询处理失败: {str(e)}"})


@app.route('/detect-dialect', methods=['POST'])
def handle_detect_dialect():
    """处理方言检测请求 - 百度版本"""
    try:
        # 获取音频数据
        if 'audio' not in request.files:
            return jsonify({"error": "没有接收到音频文件"})

        audio_file = request.files['audio']

        # 读取音频文件并转为base64
        audio_data = audio_file.read()
        audio_base64 = base64.b64encode(audio_data).decode('utf-8')

        # 调用API进行方言检测
        response = requests.post(
            f"{API_URL}/detect-dialect",
            json={"audio_base64": audio_base64}
        )

        return jsonify(response.json())

    except Exception as e:
        return jsonify({"error": f"方言检测失败: {str(e)}"})


# 新增百度服务状态检查路由
@app.route('/baidu-status')
def baidu_status():
    """查看百度语音服务状态"""
    try:
        response = requests.get(f"{API_URL}/baidu-status")
        status = response.json()
        return render_template('baidu_status.html', status=status)
    except Exception as e:
        return render_template('error.html',
                               message="无法获取百度服务状态",
                               description=str(e))


# 新增文生视频相关路由 (保持不变)
# @app.route('/video/create', methods=['GET', 'POST'])
# def create_video():
#     """创建文生视频页面"""
#     if request.method == 'GET':
#         return render_template('create_video.html')
#
#     # 处理POST请求
#     try:
#         topic = request.form.get('topic', '')
#         character_style = request.form.get('character_style', 'anime')
#         style = request.form.get('style', 'detailed')
#         duration = int(request.form.get('duration', 60))
#         language = request.form.get('language', 'mandarin')
#         voice_id = request.form.get('voice_id', '')
#
#         # 创建API请求
#         payload = {
#             "topic": topic,
#             "character_style": character_style,
#             "voice_id": voice_id if voice_id else None,
#             "style": style,
#             "duration": duration,
#             "language": language
#         }
#
#         # 调用API
#         response = requests.post(f"{API_URL}/create-video", json=payload)
#
#         if response.status_code != 200:
#             return render_template('error.html',
#                                    message="视频创建请求失败",
#                                    description=f"API返回状态码: {response.status_code}")
#
#         # 获取任务ID
#         result = response.json()
#         task_id = result.get('id')
#
#         # 重定向到任务状态页面
#         return redirect(url_for('video_task_status', task_id=task_id))
#
#     except Exception as e:
#         return render_template('error.html',
#                                message="视频创建请求失败",
#                                description=str(e))


@app.route('/video/create', methods=['GET', 'POST'])
def create_video():
    """创建视频"""
    if request.method == 'GET':
        return render_template('create_video.html')

    # 处理POST请求
    try:
        topic = request.form.get('topic', '')
        character_style = request.form.get('character_style', 'anime')
        style = request.form.get('style', 'detailed')
        duration = int(request.form.get('duration', 60))
        language = request.form.get('language', 'mandarin')
        voice_id = request.form.get('voice_id', '')

        # 创建API请求
        payload = {
            "topic": topic,
            "character_style": character_style,
            "voice_id": voice_id if voice_id else None,
            "style": style,
            "duration": duration,
            "language": language
        }

        # 调用API
        response = requests.post(f"{API_URL}/create-video", json=payload)

        if response.status_code != 200:
            return render_template('error.html',
                                   message="视频创建请求失败",
                                   description=f"API返回状态码: {response.status_code}")

        # 检查响应内容类型
        try:
            result = response.json()
        except ValueError as json_error:
            return render_template('error.html',
                                   message="视频创建请求失败",
                                   description=f"API返回无效的JSON响应: {str(json_error)}")

        # 获取任务ID并验证
        task_id = result.get('id') or result.get('task_id')

        if not task_id:
            return render_template('error.html',
                                   message="视频创建请求失败",
                                   description=f"API响应中缺少任务ID。响应内容: {result}")

        # 验证task_id不为空字符串
        if not task_id.strip():
            return render_template('error.html',
                                   message="视频创建请求失败",
                                   description="获取到空的任务ID")

        # 重定向到任务状态页面
        return redirect(url_for('video_task_status', task_id=task_id))

    except requests.exceptions.RequestException as req_error:
        return render_template('error.html',
                               message="视频创建请求失败",
                               description=f"网络请求错误: {str(req_error)}")
    except Exception as e:
        return render_template('error.html',
                               message="视频创建请求失败",
                               description=f"未知错误: {str(e)}")


# 添加调试路由来测试API连接
@app.route('/test-api', methods=['GET'])
def test_api():
    """测试API连接"""
    try:
        response = requests.get(f"{API_URL}/videos")
        return {
            "status": "success",
            "api_status": response.status_code,
            "api_url": API_URL,
            "response_preview": str(response.text)[:200]
        }
    except Exception as e:
        return {
            "status": "error",
            "error": str(e),
            "api_url": API_URL
        }


class TaskWrapper:
    """将字典转换为对象，支持属性访问"""

    def __init__(self, data):
        self._data = data

        # 确保必要字段存在
        if 'id' not in data:
            if 'task_id' in data:
                data['id'] = data['task_id']
            else:
                data['id'] = 'unknown'

        # 递归转换所有嵌套字典为对象
        for key, value in data.items():
            if isinstance(value, dict):
                setattr(self, key, TaskWrapper(value))
            elif isinstance(value, list):
                # 处理列表中的字典
                new_list = []
                for item in value:
                    if isinstance(item, dict):
                        new_list.append(TaskWrapper(item))
                    else:
                        new_list.append(item)
                setattr(self, key, new_list)
            else:
                setattr(self, key, value)

    def __getattr__(self, name):
        """如果属性不存在，返回None而不是报错"""
        return None

    def __repr__(self):
        return f"TaskWrapper({self._data})"


@app.route('/video/task/<task_id>', methods=['GET'])
def video_task_status(task_id):
    """查看任务状态 - 完整修复版"""
    try:
        logger.info(f"获取任务状态: {task_id}")

        # 获取任务状态
        response = requests.get(f"{API_URL}/video-task/{task_id}")

        if response.status_code == 404:
            return render_template('error.html',
                                   message="任务未找到",
                                   description=f"任务ID {task_id} 不存在")

        if response.status_code != 200:
            return render_template('error.html',
                                   message="无法获取任务状态",
                                   description=f"API返回状态码: {response.status_code}")

        # 解析任务数据
        task_data = response.json()
        logger.info(f"原始任务数据键: {list(task_data.keys()) if isinstance(task_data, dict) else 'Not dict'}")

        # 🔧 关键修复：转换为对象包装器
        task_wrapper = TaskWrapper(task_data)

        logger.info(f"任务状态: {task_wrapper.status}, ID: {task_wrapper.id}")

        # 根据任务状态显示不同页面
        status = task_wrapper.status

        if status == 'completed':
            # 验证完成任务的必要字段
            if not hasattr(task_wrapper, 'result') or not task_wrapper.result:
                return render_template('error.html',
                                       message="任务结果缺失",
                                       description="任务显示为已完成，但缺少结果数据")

            logger.info("渲染视频结果页面")
            return render_template('video_result.html', task=task_wrapper)

        elif status == 'failed':
            error_message = getattr(task_wrapper, 'message', '视频生成失败')
            return render_template('error.html',
                                   message="视频生成失败",
                                   description=error_message)
        else:
            # 处理中状态
            logger.info("渲染视频处理页面")
            return render_template('video_processing.html', task=task_wrapper)

    except requests.exceptions.ConnectionError:
        return render_template('error.html',
                               message="连接失败",
                               description="无法连接到视频处理服务")

    except requests.exceptions.Timeout:
        return render_template('error.html',
                               message="请求超时",
                               description="获取任务状态超时")

    except Exception as e:
        logger.error(f"获取任务状态失败: {str(e)}")
        logger.error(f"错误类型: {type(e)}")

        # 详细错误信息
        import traceback
        logger.error(f"完整错误堆栈: {traceback.format_exc()}")

        return render_template('error.html',
                               message="获取任务状态失败",
                               description=f"系统错误: {str(e)}")


# 🧪 增强的调试路由
@app.route('/debug/task/<task_id>', methods=['GET'])
def debug_task_data(task_id):
    """详细调试任务数据"""
    try:
        response = requests.get(f"{API_URL}/video-task/{task_id}")

        debug_info = {
            "api_status": response.status_code,
            "task_id": task_id
        }

        if response.status_code != 200:
            debug_info.update({
                "error": f"API返回状态码: {response.status_code}",
                "response_text": response.text[:1000]
            })
            return jsonify(debug_info)

        # 解析数据
        task_data = response.json()
        debug_info.update({
            "parse_success": True,
            "data_type": str(type(task_data)),
            "original_keys": list(task_data.keys()) if isinstance(task_data, dict) else "Not dict",
            "has_id": "id" in task_data if isinstance(task_data, dict) else False,
            "has_task_id": "task_id" in task_data if isinstance(task_data, dict) else False,
            "has_status": "status" in task_data if isinstance(task_data, dict) else False,
            "has_request": "request" in task_data if isinstance(task_data, dict) else False,
            "has_result": "result" in task_data if isinstance(task_data, dict) else False,
        })

        if isinstance(task_data, dict):
            debug_info["status_value"] = task_data.get("status", "missing")
            debug_info["original_data"] = task_data

            # 测试包装器
            try:
                wrapper = TaskWrapper(task_data)
                debug_info.update({
                    "wrapper_success": True,
                    "wrapper_id": wrapper.id,
                    "wrapper_status": wrapper.status,
                    "wrapper_has_request": hasattr(wrapper, 'request'),
                    "wrapper_has_result": hasattr(wrapper, 'result')
                })

                # 测试request字段
                if hasattr(wrapper, 'request'):
                    debug_info["request_type"] = str(type(wrapper.request))
                    if hasattr(wrapper.request, 'topic'):
                        debug_info["request_topic"] = wrapper.request.topic

            except Exception as wrapper_error:
                debug_info.update({
                    "wrapper_success": False,
                    "wrapper_error": str(wrapper_error)
                })

        return jsonify(debug_info)

    except Exception as e:
        return jsonify({
            "error": str(e),
            "task_id": task_id,
            "debug_failed": True
        }), 500

# 增强的错误处理中间件
@app.errorhandler(500)
def internal_error(error):
    """处理500错误"""
    logger.error(f"Internal server error: {str(error)}")
    return render_template('error.html',
                           message="服务器内部错误",
                           description="请联系系统管理员或稍后重试"), 500


@app.errorhandler(404)
def not_found_error(error):
    """处理404错误"""
    return render_template('error.html',
                           message="页面未找到",
                           description="请检查URL是否正确"), 404

@app.route('/video/list', methods=['GET'])
def list_videos():
    """视频库列表"""
    try:
        response = requests.get(f"{API_URL}/videos")

        if response.status_code != 200:
            return render_template('error.html',
                                   message="无法获取视频列表",
                                   description=f"API返回状态码: {response.status_code}")

        result = response.json()
        videos = result.get('videos', [])

        return render_template('video_library.html', videos=videos)

    except Exception as e:
        return render_template('error.html',
                               message="获取视频列表失败",
                               description=str(e))


@app.route('/video/view/<video_id>', methods=['GET'])
def view_video(video_id):
    """查看单个视频"""
    try:
        response = requests.get(f"{API_URL}/video/{video_id}")

        if response.status_code != 200:
            return render_template('error.html',
                                   message="无法获取视频信息",
                                   description=f"API返回状态码: {response.status_code}")

        result = response.json()
        video = result.get('video', {})
        script = result.get('script', None)

        return render_template('video_details.html', video=video, script=script)

    except Exception as e:
        return render_template('error.html',
                               message="获取视频信息失败",
                               description=str(e))


@app.route('/generate-enhanced-image', methods=['POST'])
def generate_enhanced_image():
    """代理到FastAPI的增强图像生成"""
    try:
        # 获取前端请求数据
        request_data = request.get_json()

        if not request_data:
            return jsonify({"error": "请求数据为空"}), 400

        print(f"📨 收到增强图像生成请求: {request_data.get('prompt', 'N/A')[:30]}...")

        # 转发到FastAPI服务
        response = requests.post(
            f"{API_URL}/generate-enhanced-image",
            json=request_data,
            headers={"Content-Type": "application/json"},
            timeout=180  # 3分钟超时
        )

        print(f"📡 FastAPI响应状态: {response.status_code}")

        # 返回FastAPI的响应
        if response.status_code == 200:
            return jsonify(response.json())
        else:
            error_msg = f"FastAPI错误: {response.status_code}"
            try:
                error_detail = response.json()
                error_msg = error_detail.get("detail", error_msg)
            except:
                pass
            return jsonify({"error": error_msg}), response.status_code

    except requests.exceptions.Timeout:
        print("❌ 图像生成超时")
        return jsonify({"error": "图像生成超时，请稍后重试"}), 408
    except requests.exceptions.ConnectionError:
        print("❌ 无法连接FastAPI服务")
        return jsonify({"error": "无法连接到图像生成服务，请确保FastAPI服务运行"}), 503
    except Exception as e:
        print(f"❌ 生成失败: {str(e)}")
        return jsonify({"error": f"生成失败: {str(e)}"}), 500


# 同时添加其他可能缺失的图像编辑路由

@app.route('/edit-image-vase', methods=['POST'])
def edit_image_vase():
    """代理到FastAPI的花瓶替换功能"""
    try:
        request_data = request.get_json()
        if not request_data:
            return jsonify({"error": "请求数据为空"}), 400

        image_id = request_data.get('image_id')
        new_vase_style = request_data.get('new_vase_style')

        if not image_id or not new_vase_style:
            return jsonify({"error": "缺少必要参数"}), 400

        print(f"🏺 替换花瓶: {image_id} -> {new_vase_style}")

        response = requests.post(
            f"{API_URL}/edit-image-vase",
            params={"image_id": image_id, "new_vase_style": new_vase_style},
            timeout=120
        )

        return jsonify(response.json()), response.status_code

    except Exception as e:
        return jsonify({"error": f"花瓶替换失败: {str(e)}"}), 500


@app.route('/edit-image-color', methods=['POST'])
def edit_image_color():
    """代理到FastAPI的颜色修改功能"""
    try:
        request_data = request.get_json()
        if not request_data:
            return jsonify({"error": "请求数据为空"}), 400

        image_id = request_data.get('image_id')
        target_color = request_data.get('target_color')

        if not image_id or not target_color:
            return jsonify({"error": "缺少必要参数"}), 400

        print(f"🎨 修改花朵颜色: {image_id} -> {target_color}")

        response = requests.post(
            f"{API_URL}/edit-image-color",
            params={"image_id": image_id, "target_color": target_color},
            timeout=120
        )

        return jsonify(response.json()), response.status_code

    except Exception as e:
        return jsonify({"error": f"颜色修改失败: {str(e)}"}), 500


@app.route('/edit-image-lighting', methods=['POST'])
def edit_image_lighting():
    """代理到FastAPI的光照增强功能"""
    try:
        request_data = request.get_json()
        if not request_data:
            return jsonify({"error": "请求数据为空"}), 400

        image_id = request_data.get('image_id')
        lighting_style = request_data.get('lighting_style')

        if not image_id or not lighting_style:
            return jsonify({"error": "缺少必要参数"}), 400

        print(f"💡 光照增强: {image_id} -> {lighting_style}")

        response = requests.post(
            f"{API_URL}/edit-image-lighting",
            params={"image_id": image_id, "lighting_style": lighting_style},
            timeout=120
        )

        return jsonify(response.json()), response.status_code

    except Exception as e:
        return jsonify({"error": f"光照增强失败: {str(e)}"}), 500


@app.route('/batch-generate-styles', methods=['POST'])
def batch_generate_styles():
    """代理到FastAPI的批量生成风格功能"""
    try:
        request_data = request.get_json()
        if not request_data:
            return jsonify({"error": "请求数据为空"}), 400

        print(f"🎭 批量生成风格: {request_data.get('prompt', 'N/A')[:30]}...")

        response = requests.post(
            f"{API_URL}/batch-generate-styles",
            json=request_data,
            headers={"Content-Type": "application/json"},
            timeout=300  # 5分钟超时
        )

        return jsonify(response.json()), response.status_code

    except Exception as e:
        return jsonify({"error": f"批量生成失败: {str(e)}"}), 500


@app.route('/composition-variants', methods=['POST'])
def composition_variants():
    """代理到FastAPI的构图变体功能"""
    try:
        request_data = request.get_json()
        if not request_data:
            return jsonify({"error": "请求数据为空"}), 400

        print(f"📐 生成构图变体: {request_data.get('prompt', 'N/A')[:30]}...")

        response = requests.post(
            f"{API_URL}/composition-variants",
            json=request_data,
            headers={"Content-Type": "application/json"},
            timeout=300  # 5分钟超时
        )

        return jsonify(response.json()), response.status_code

    except Exception as e:
        return jsonify({"error": f"构图变体生成失败: {str(e)}"}), 500

# 创建文生视频功能所需的目录
def create_required_directories():
    """创建文生视频功能所需的目录"""
    directories = [
        "static/videos",
        "static/images",
        "static/audio",
        "static/temp",
        "static/tasks"
    ]

    for directory in directories:
        os.makedirs(directory, exist_ok=True)


# 确保目录存在
create_required_directories()

if __name__ == '__main__':
    app.run(debug=True, port=5000)